<?php
@set_time_limit(0);
@ob_start();
@session_start();
error_reporting (E_ALL ^ E_NOTICE);
require_once("../../includes/GPSFunction.php");
require_once("../../includes/smsSF.php"); 
//	DB Connection
require("../../includes/config.inc.php"); 
require("../../includes/Database.class.php"); 

$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 

function chk_folder($filename)
{
	$fp_load = @fopen("$filename", "rb");
	if ( $fp_load )
	{
		return true;
	}
	else
	{
		return false;
	}
}

function gpspathFun($source)
{
	$file1 = @fopen($source, "r");
	if($file1)
	{
		while(!@feof($file1))
		{
		   $data= @fgets($file1);				 
		   //$i++;
		}
		$data = getSortedData($data);
		return $data;
		
	}
	else
	{
		return 0;
	}
	@fclose($file1);
}
function kmsPerDay($path1)
{ 
	//echo 'ss'.$path1;
	$timeArr = array();
	$cnt = 1;
	$totalDistance = 0;
	//$geocode = get_url($path1);
	
  	$file1 = @fopen($path1, "r");
	if($file1)
	{
		//echo $path1;
		while(!feof($file1))
		{
			
			$data= @fgets($file1);				 
		}
		$data = getSortedData($data);
		$data1=explode("#",$data);
		//print_r($data1);
		for($j1=0;$j1<count($data1);$j1++)
		{
			$data2=explode("@",$data1[$j1]);
			if(count($data2)>1)
			{
				$data3=explode(",",$data2[1]);	
				$vehi=$data3[0];
				
				$geodate = $data3[8];
				$geoTime = date("h:i A",strtotime($data3[9]));
				
				$pos1=calLat($data3[2]);
				$pos2=calLong($data3[1]);
				if($pos1>0 && $pos2>0)
				{
					if(!in_array($geoTime,$timeArr))
					{
						if($j1==0)
						{
							$pits1 =  $pos1;
							$pits2 =  $pos2;
						}
						else
						{
							$pits3 =  $pos1;
							$pits4 =  $pos2;
							
							$dist = getDistance($pits1, $pits2, $pits3, $pits4);
							$totalDistance += $dist;
							$pits1 =  $pits3;
							$pits2 =  $pits4;
						}
				
					}
				}
			}
			array_push($timeArr,$geoTime);
		}
		//$findLatLng = $pits1.",".$pits2;
		$locat = simpleGeocode($pits1,$pits2);
 		//$locat=getGeocode($findLatLng,"ADDRESS");
 		$locat = str_replace(",","-",$locat); 
		$finalData = round($totalDistance).",".$locat.",".$data3[3].",".$geodate.",".$geoTime;

		@fclose($file1);
		return $finalData;
	}
	else
	{
		return false;
	}
}

if(isset($_GET[add_stop_name]) && $_GET[add_stop_name] !='')
{
	//echo $_GET[add_stop_name];
	$getCont =  "select * from tb_geofence_info where (tgi_name = '".$_GET[add_stop_name]."' OR tgi_latLong = '".$_GET[mapPt]."') AND tgi_clientId =".$_SESSION[clientID];
	$resCont = $db->query($getCont);
	if($db->affected_rows == 0)
	{
		$cdata["tgi_clientId"] = $_SESSION[clientID];
		$cdata["tgi_name"] = $_GET[add_stop_name];
		$cdata["tgi_isActive"] = 1;
		$cdata["tgi_radius"] = "0.50";
		$cdata["tgi_latLong"] = $_GET[mapPt];
		//print_r($cdata);
		//exit;
		if($db->query_insert("tb_geofence_info", $cdata))
		{
			echo 1;
		}
		else
		{
			echo 0;
		}
	}
	else
		echo 0;
}

if(isset($_GET[FetchUDLoca]) && $_GET[FetchUDLoca]!='')
{
	//$latlng = $_GET[lat].','.$_GET[lng];
	//$vehiAddr=getGeocode($latlng,'ADDRESS');
	$vehiAddr = getMyGeoAddress($_GET[lat],$_GET[lng]);
	if(!$vehiAddr)
	{
		echo $_GET[addr]; 
	}
	else
	{
		echo $vehiAddr;
	}
	/*exit;
	$getCont = "select * from tb_geofence_info where tgi_geoAddress = '".addslashes($_GET[addr])."' AND tgi_clientId =".$_SESSION[clientID];
	$resCont = $db->query($getCont);
	$totCont = $db->affected_rows;
	if($totCont > 0)
	{
		if($totCont == 1)
		{
			$fetCont = $db->fetch_array($resCont);
			echo $fetCont[tgi_name];
		}
		elseif($totCont > 1)
		{
			while($fetCont = $db->fetch_array($resCont))
			{
				$lat_lng = explode(",",$fetCont[tgi_latLong]);		
				$radius = $fetCont[tgi_radius];
				$latlngArr = drawCircle($lat_lng[0],$lat_lng[1],$radius);
				//print_r($latlngArr);
				if(getGeofenceStatus($latlngArr,$_GET[lat],$_GET[lng]) == 1)
				{
					echo 'ss'.$fetCont[tgi_name];
					break;
				}
				else
				{
				}
			}
		}
	}
	else
	{
		echo $_GET[addr];
	}*/
}
if(isset($_GET[getRouteList]) && $_GET[getRouteList]!='')
{
	$getCont =  "select * from tb_route_info where tri_id =".$_GET[getRouteList];
	$resCont = $db->query($getCont);
	$str = '';
	if($db->affected_rows > 0)
	{
		$fetCont = $db->fetch_array($resCont);
		$geoIds = explode("#",$fetCont[tri_geofenceIds]);
		for($t = 0;$t <count($geoIds)-1;$t++)
		{
			$q1 =  "select * from tb_geofence_info where tgi_id =".$geoIds[$t];
			$r1 = $db->query($q1);
			
			if($db->affected_rows > 0)
			{
				$f1 = $db->fetch_array($r1);
				$str .= $geoIds[$t]."#".$f1[tgi_name]."#".$fetCont[tri_deviceId]."@";	
			}
		}
	}
	echo $str;
}

if(isset($_GET[sendSMS]) && $_GET[sendSMS]!='')
{
	$getReseller = "select * from tb_clientinfo where ci_id = ".$_GET[resell];
	$resReseller = mysql_query($getReseller);
	$fetReseller = mysql_fetch_assoc($resReseller);
	
	$smsMsg = $_GET[mesg];
	$smsMsg .= " - ".$fetReseller[ci_clientName];
	
	$mobileSrc = $_GET[numbers];
	$smsres = sendGatewaySMS($from,$mobileSrc,$smsMsg,$fetReseller[ci_smsGatewayUri],$fetReseller[ci_smsGatewayUsername],$fetReseller[ci_smsGatewayPassword],$fetReseller[ci_smsGatewaySenderId]);
	if($smsres)
	{
		$smsdata['tcssi_client_id'] = $_GET[resell];
		$smsdata['tcssi_mobile_nos'] = $mobileSrc;
		$smsdata['tcssi_message'] = $smsMsg;
		$smsdata['tcssi_status'] = $smsres;
		$smsdata['tcssi_datesend'] = "NOW()";		
		//print_r($smsdata);		
//		exit;
		if($db->query_insert("tb_client_send_sms_info", $smsdata))
		$res =  1;
		else $res = 0;
	} else $res = 0;
	
	echo $res;
}

if($_POST[txtUserId] != '' && $_POST[txtClientId] != '')
{
	echo '<span style="color:red;">Redirecting...</span>';
	$_SESSION[userID] = $_POST[txtUserId];
	$_SESSION[clientID] = $_POST[txtClientId];
	$_SESSION[ResellID] = $_POST[ResellID];

	header("location:../../modules/user/");
	exit;
}
//print_r($_POST);
if(isset($_POST[txtSuperID]) && $_POST[txtSuperID] != '')
{
	if(isset($_POST[adminType]) && $_POST[adminType] == 'S')
	{
		echo '<span style="color:red;">Redirecting...</span>';
		unset($_SESSION[userID]);
		unset($_SESSION[clientID]);
		$_SESSION[superID] = $_POST[txtSuperID];
		header("location:../../modules/sa/");
		exit;
	}
	else if(isset($_POST[adminType]) && $_POST[adminType] == 'R')
	{
		echo '<span style="color:red;">Redirecting...</span>';
		unset($_SESSION[userID]);
		unset($_SESSION[clientID]);
		unset($_SESSION[ResellID]);

		$sql = "SELECT * FROM tb_userinfo WHERE ui_clientId = '".$_POST[txtSuperID]."' AND ui_isAdmin  = 1";
		$rows = $db->query($sql);
		if($db->affected_rows > 0)
		{
			 $recordUserInfo = $db->fetch_array($rows);
             if($recordUserInfo[ci_clientId]==0)
			 {
				 $_SESSION[userID] = $recordUserInfo[ui_id];
				 $_SESSION[clientID] = $recordUserInfo[ui_clientId];
			 }
		}
		header("location:../../modules/user/?ch=viewClient");
		exit;
	}
}
if(isset($_GET[drivertype]) && $_GET[drivertype]!='')
{
	if($_GET[drivertype] == 'add')
	{
		$chkCont = "select * from tb_client_contact_info where tcci_source = ".$_GET[src]." AND tcci_clientId =".$_SESSION[clientID];
		$resCont = $db->query($chkCont);
		if($db->affected_rows == 0)
		{
			$cdata["tcdi_clientId"] = $_SESSION[clientID];
			$cdata["tcdi_driverName"] = $_GET[name];
			$cdata["tcdi_mobile"] = $_GET[src];
			$cdata["tcdi_licenseNo"] = $_GET[license];
			$cdata["tcdi_dob"] = date("Y-m-d",strtotime($_GET[dob]));
			
			if($db->query_insert("tb_client_driver_info", $cdata))
			{
				echo 1;
			}
			else
			{
				echo 0;
			}
		}
		else echo 2;
	}
	else
	{
		$cdata["tcdi_driverName"] = $_GET[name];
		$cdata["tcdi_mobile"] = $_GET[src];
		$cdata["tcdi_licenseNo"] = $_GET[license];
		$cdata["tcdi_dob"] = date("Y-m-d",strtotime($_GET[dob]));
		//print_r($_GET);
		//exit;
		
		if($db->query_update("tb_client_driver_info", $cdata, "tcdi_id = ".$_GET[cid]))
			echo 3;
		else echo 4;
	}
}
if(isset($_POST[id]) && $_POST[id]!='')
{
	$spltEditId = explode("_",$_POST[id]);
	if($spltEditId[0] =="odo")
	{
		$getLiveData = "SELECT * FROM tb_livegps_info WHERE tli_imei = '".$spltEditId[1]."'";
		$exeLiveData = $db->query($getLiveData);
		if($db->affected_rows > 0)
		{
			$fetLiveData = $db->fetch_array($exeLiveData);
			
			$devOdometer['di_odoMeter'] = $_POST[value];
			
			$db->query_update("tb_deviceinfo", $devOdometer, "di_imeiId = ".$spltEditId[1]);
			
			$livedata["tli_distance"] = $_POST[value];
			//print_r($livedata);
			//exit;
			if($db->query_update("tb_livegps_info", $livedata, "tli_imei = ".$spltEditId[1]))
			 	echo $_POST[value];
			else
				echo 0;
		}
	}
}
if(isset($_GET[immbolize]) && $_GET[immbolize]!='')
{
	$getData = "SELECT * FROM tb_deviceinfo,tb_clientinfo,tb_device_model WHERE model = di_deviceModel AND ci_id = di_clientId AND di_id = ".$_GET[devId];
	$resData = mysql_query($getData);
	if(@mysql_affected_rows() > 0)
	{
		$fetData = mysql_fetch_assoc($resData);
		//print_r($fetData);
	
		$getReseller = "select * from tb_clientinfo where ci_id = ".$fetData[ci_clientId];
		$resReseller = mysql_query($getReseller);
		$fetReseller = @mysql_fetch_assoc($resReseller);
	}
	
	if($_GET[immbolize] == 1)
	{
		//send sms
		$from = "";
		$to = $fetData[di_mobileNo];
		$outStr = "1".str_repeat("0", ($fetData[tdm_noofOutputs]-1));
		$msg = "opa opa setdigout ".$outStr;
		$smsres = sendGatewaySMS($from,$to,$msg,$fetReseller[ci_smsGatewayUri],$fetReseller[ci_smsGatewayUsername],$fetReseller[ci_smsGatewayPassword],$fetReseller[ci_smsGatewaySenderId]);

		if($smsres)
		{
			$cdata["tii_clientId"] = $_GET[cltId];
			$cdata["tii_devId"] = $_GET[devId];
			$cdata["tii_status"] = 1;
			$cdata["tii_mobileNo"] = $to;
			$cdata["tii_stopMsg"] = $msg;
			$cdata["tii_smsStatus"] = $smsres;
			//print_r($cdata);
			//exit;
			if($primary_id = $db->query_insert("tb_immbolize_info", $cdata))
			{
				echo $primary_id;
			}
			else
			{
				echo 0;
			}
		}
	}
	else
	{
		//send sms
		$from = "";
		$to =  $fetData[di_mobileNo];
		$outStr = "0".str_repeat("0", ($fetData[tdm_noofOutputs]-1));
		$msg = "opa opa setdigout ".$outStr;
		$smsres= sendGatewaySMS($from,$to,$msg,$fetReseller[ci_smsGatewayUri],$fetReseller[ci_smsGatewayUsername],$fetReseller[ci_smsGatewayPassword],$fetReseller[ci_smsGatewaySenderId]);

		if($smsres)
		{
			$cdata["tii_status"] = 2;
			$cdata["tii_startMsg"] = $msg;
			$cdata["tii_smsStatus"] = $smsres;
			$cdata["tii_updateDate"] = date("Y-m-d H:i:s");
			//print_r($cdata);
			//exit;
			if($db->query_update("tb_immbolize_info", $cdata, "tii_id = ".$_GET[immId]))
			{
				echo -1;
			}
			else
			{
				echo 0;
			}
		}
	}
}
if(isset($_GET[upGeoStatus]) && $_GET[upGeoStatus]!='')
{
	$getDeviceGeofence = "SELECT * FROM tb_assigngeofence WHERE tag_geofenceId  = ".$_GET[geoid];	
	$resDeviceGeofence = $db->query($getDeviceGeofence);
		
	if($db->affected_rows == 0 )
	{
		$sql = "UPDATE tb_geofence_info SET tgi_isActive = ".$_GET[status]." WHERE tgi_id = ".$_GET[geoid]." AND tgi_clientId = ".$_SESSION[clientID];
		$row = $db->query($sql); 
		if($row)
			echo 4;
		else
			echo 5;
	}
	else
		echo 5;
}
if(isset($_GET[deletePoint]) && $_GET[deletePoint]!='')
{
	$sql = "DELETE from tb_assigngeofence WHERE tag_geofenceId  = ".$_GET[param]." AND tag_clientId = ".$_SESSION[clientID];
	$row = $db->query($sql); 
	
	$sql1 = "DELETE from tb_geofence_info WHERE tgi_id = ".$_GET[param]." AND tgi_clientId = ".$_SESSION[clientID];
	$row1 = $db->query($sql1); 
	if($row1)
		echo 4;
	else
		echo 5;
}
if(isset($_GET[addGeoPoint]) && $_GET[addGeoPoint]!='')
{
	if($_GET[todo] == 0)
	{
		$sql =  "select * from tb_geofence_info where tgi_name = '".$_GET[name]."' AND tgi_clientId =".$_SESSION[clientID];
		$res = $db->query($sql);
		if($db->affected_rows == 0)
		{
			$cdata["tgi_clientId"] = $_SESSION[clientID];
			$cdata["tgi_name"] = $_GET[name];
			$cdata["tgi_isActive"] = 1;
			$cdata["tgi_radius"] = $_GET[radius];
			$cdata["tgi_latLong"] = $_GET[param];
			$cdata["tgi_geoAddress"] = $_GET[geoloca];
			//print_r($cdata);
			//exit;
			if($primary_id = $db->query_insert("tb_geofence_info", $cdata))
			{
				echo $primary_id;
			}
			else
			{
				echo 0;
			}
		}
		else
		{
			echo -5;
		}
	}
	else if($_GET[todo] > 0)
	{

		$getCont = "select * from tb_geofence_info where tgi_id = '".$_GET[todo]."' AND tgi_clientId =".$_SESSION[clientID];
		$resCont = $db->query($getCont);
		$fetCont = $db->fetch_array($resCont);
		$cdata["tgi_clientId"] = $_SESSION[clientID];
		$cdata["tgi_name"] = $_GET[name];
		$cdata["tgi_isActive"] = 1;
		$cdata["tgi_radius"] = $_GET[radius];
		$cdata["tgi_latLong"] = $_GET[param];
		$cdata["tgi_geoAddress"] = $_GET[geoloca];
		//print_r($cdata);
		//exit;
		if($db->query_update("tb_geofence_info", $cdata, "tgi_id = ".$fetCont[tgi_id]))
		{
			echo $fetCont[tgi_id];
		}
		else
		{
			echo 0;
		}
	}
}
if(isset($_GET[getAlertListforAnalog]) && $_GET[getAlertListforAnalog]!='')
{
	$getCont =  "select di_analogPort from tb_deviceinfo,tb_device_model where id = di_deviceModel AND di_id =".$_GET[getAlertListforAnalog];
	$resCont = $db->query($getCont);
	$str = '';
	if($db->affected_rows > 0)
	{
		$fetCont = $db->fetch_array($resCont);
		/*if($fetCont[di_immoblize] == 1)
			$str = $fetCont[alerts].','.$fetCont[di_portDetails].',Immbolize';
		else*/
		if($fetCont[di_analogPort])
		$str = $fetCont[di_analogPort];		
	}
	echo $str;
}
if(isset($_GET[getAlertListfor]) && $_GET[getAlertListfor]!='')
{
	$getCont =  "select di_inputPort,di_outputPort from tb_deviceinfo,tb_device_model where id = di_deviceModel AND di_id =".$_GET[getAlertListfor];
	$resCont = $db->query($getCont);
	$str = '';
	if($db->affected_rows > 0)
	{
		$fetCont = $db->fetch_array($resCont);
		/*if($fetCont[di_immoblize] == 1)
			$str = $fetCont[alerts].','.$fetCont[di_portDetails].',Immbolize';
		else*/
		if($fetCont[di_inputPort])
		$str = $fetCont[di_inputPort];		
		
		if($fetCont[di_outputPort])
			$str .= $fetCont[di_outputPort];
	}
	echo $str;
}
if(isset($_GET[contType]) && $_GET[contType]!='')
{
	$getCont =  "select * from tb_client_contact_info where tcci_srcType = '".$_GET[contType]."' AND tcci_clientId =".$_SESSION[clientID];
	$resCont = $db->query($getCont);
	$str = '';
	if($db->affected_rows > 0)
	{
		while($fetCont = $db->fetch_array($resCont))
		{
			//print_r($fetCont);
			$str .='<option value='.$fetCont[tcci_source].'>'.$fetCont[tcci_source].'</option>';
		}
	}
	echo $str;
}
if(isset($_GET[type]) && $_GET[type]!='')
{
	if($_GET[type] == 'add')
	{
		$chkCont = "select * from tb_client_contact_info where tcci_source = '".$_GET[src]."' AND tcci_clientId =".$_SESSION[clientID];
		$resCont = $db->query($chkCont);
		if($db->affected_rows == 0)
		{
			$cdata["tcci_clientId"] = $_SESSION[clientID];
			$cdata["tcci_name"] = $_GET[name];
			$cdata["tcci_srcType"] = $_GET[alrttype];
			$cdata["tcci_source"] = $_GET[src];
			if($db->query_insert("tb_client_contact_info", $cdata))
			{
				echo 1;
			}
			else
			{
				echo 0;
			}
		}
		else echo 2;
	}
	else
	{
		$cdata["tcci_name"] = $_GET[name];
		$cdata["tcci_srcType"] = $_GET[alrttype];
		$cdata["tcci_source"] = $_GET[src];
		
		//print_r($_GET);
		
		if($db->query_update("tb_client_contact_info", $cdata, "tcci_id = ".$_GET[cid]))
			echo 3;
		else echo 4;
	}
}
if($_GET[getResQryWithHash] !='' && $_GET[getResQryWithHash] !='')
{
	$rows = $db->query($_GET[getResQryWithHash]);
	if($db->affected_rows > 0)
	{
		$fetch = @mysql_fetch_assoc($rows); 
		//print_r($fetch);
		echo implode("#",$fetch);
	}
	else echo 0;
}
if($_GET[getResQry] !='' && $_GET[getResQry] !='')
{
	$rows = $db->query($_GET[getResQry]);
	if($db->affected_rows > 0)
	{
		$fetch = @mysql_fetch_assoc($rows); 
		//print_r($fetch);
		echo implode(",",$fetch);
	}
	else echo 0;
}
if($_GET[ajaxQry] !='' && $_GET[ajaxQry] !='')
{
	$rows = $db->query($_GET[ajaxQry]);
	echo $db->affected_rows;
}
if($_GET[date_offline] !='' && $_GET[devImei] !='')
{
	$getDevice = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE di_imeiId = '".$_GET[devImei]."' AND tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." ORDER BY di_deviceName,di_deviceId ASC";
	$resDevice= $db->query($getDevice);	
	//exit;
	$tmpId='';
	$destArr=array();
	
	if($db->affected_rows > 0 )
	{
		while ($fetDevice = $db->fetch_array($resDevice)) 
		{
			$sdate = date("d-m-Y",strtotime($fetDevice[di_createDate]));
			$edate = date("d-m-Y");
			
			$z = GetDays($sdate, $edate);
			//print_r($z);exit;
			
			for($y=count($z)-1; $y>0; $y--)
			{					
				//echo $z[$y]."<br>";	
				$sToTime = strtotime($z[$y]);
				$eToTime = strtotime(date("d-m-Y"));
				$path=DATAPATH.date('d-m-Y',strtotime($z[$y]))."/".$fetDevice[di_imeiId].".txt";
				if($sToTime == $eToTime )
				{
					//echo $sToTime." == ".$eToTime."<br>";
					//$path=DATAPATH.date('d-m-Y',strtotime($z[$y]))."/".$fetDevice[di_imeiId].".txt";
					$km = explode(",",kmsPerDay($path));
					if($km[0] !=0)
					{
						$getDateReading = "SELECT * FROM tb_speed_meter_info WHERE tmsi_clientId = ".$fetDevice[di_clientId]." AND tmsi_imei = '".$fetDevice[di_imeiId]."' AND tmsi_readDate = '".date('Y-m-d',strtotime($z[$y]))."'";
						$resDateReading = $db->query($getDateReading);
		
						if($db->affected_rows == 0)
						{
							
							$kmdata['tmsi_clientId'] = $fetDevice[di_clientId];
							$kmdata['tmsi_imei'] = $fetDevice[di_imeiId];
							$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($z[$y]));
							$kmdata['tmsi_kmpd'] = $km[0];
							
							//print_r($kmdata);
							//exit;
							$db->query_insert("tb_speed_meter_info", $kmdata);
						}
						else
						{
							$fetDateReading = $db->fetch_array($resDateReading);
							$kmdata['tmsi_clientId'] = $fetDevice[di_clientId];
							$kmdata['tmsi_imei'] = $fetDevice[di_imeiId];
							$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($z[$y]));
							$kmdata['tmsi_kmpd'] = $km[0];
							
							//print_r($kmdata);
							//exit;
							$db->query_update("tb_speed_meter_info", $kmdata, "tsmi_id = ".$fetDateReading[tsmi_id]);
						}
						break;
					}
					
				}
				else
				{
					
					$fp_load = chk_folder($path);
					if ($fp_load)
					{
						//echo 'else'.$z[$y]."<br>";
						//$lastPath = $path;
						$km = explode(",",kmsPerDay($path));
						/*$datDate1 = $z[$y];*/
						break;
					}
				}					
				
			}
			//print_r($km);
		}
		$getReading = "SELECT SUM(tmsi_kmpd) as dist FROM tb_speed_meter_info WHERE tmsi_clientId = ".$_SESSION[clientID]." AND tmsi_imei = '".$_GET[devImei]."' group by tmsi_imei";
		$resReading = $db->query($getReading);
		//exit;
		//print_r($km);
		if($db->affected_rows > 0 )
		{
		
			$fetReading = mysql_fetch_assoc($resReading);
			$odoMeter = $fetDevice[di_odoMeter] + $fetReading[dist];
		}
		else
		{
			$odoMeter = $fetDevice[di_odoMeter];
		}
		if(count($km) > 0)
		{
			echo implode(",",$km).','.$odoMeter;
		}
		else
		{
			echo '0';
		}
	}
}

if($_GET[date_offline] !='' && $_GET[sessionid] !='')
{
	if(isset($_GET[date_offline]) && $_GET[date_offline])
		$date_offline = $_GET[date_offline];
	else
		$date_offline = date('d-m-Y');
	
	$getUserInfo = "SELECT * FROM tb_userinfo,tb_clientinfo WHERE ui_id  = ".$_SESSION[userID]." AND ci_id = ".$_GET[sessionid];
	$resUserInfo = $db->query($getUserInfo);

	if($db->affected_rows > 0){
	$recordUserInfo = $db->fetch_array($resUserInfo);
	}
	
	if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
	{
		$getDevice = "SELECT * FROM tb_deviceinfo,tb_client_subscription,tb_clientinfo WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=ci_id AND ci_id=".$_GET[sessionid]." order by di_deviceName,di_deviceId,ci_clientName ASC";
	}
	else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
	{
		$getDevice = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
	}
	else if($recordUserInfo[ci_clientType] == "Reseller")
	{
		$getDevice = "SELECT * FROM tb_deviceinfo,tb_clientinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId = ci_id AND ci_clientId=".$_GET[sessionid]." order by di_deviceName,di_deviceId,ci_clientName ASC";
	}
	
	$resDevice= $db->query($getDevice);	
	//exit;
	$tmpId='';
	$destArr=array();
	
	if($db->affected_rows > 0 )
	{
		while ($fetDevice = $db->fetch_array($resDevice)) 
		{
			//print_r($fetDevice);
			if($fetDevice[di_deviceName])
				$devName = $fetDevice[di_deviceName];
			else
				$devName = $fetDevice[di_deviceId];
			$devImage = $fetDevice[di_deviceImg];
				
			$renewDate = date("d-m-Y",strtotime("-1 days ".($fetDevice[tcs_noOfMonths]) ."months ".$fetDevice[tcs_renewalDateFrom]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime($date_offline) <= strtotime($renewDate))
			{
				$sdate = date("d-m-Y",strtotime($fetDevice[di_createDate]));
				$edate = date("d-m-Y");
				
				$z = GetDays($sdate, $edate);
				//print_r($z);exit;
				
				for($y=count($z)-1; $y>0; $y--)
				{					
					//echo $z[$y]."<br>";	
					$sToTime = strtotime($z[$y]);
					$eToTime = strtotime(date("d-m-Y"));
					$path=DATAPATH.date('d-m-Y',strtotime($z[$y]))."/".$fetDevice[di_imeiId].".txt";
					if($sToTime == $eToTime )
					{
						//echo $sToTime." == ".$eToTime."<br>";
						//$path=DATAPATH.date('d-m-Y',strtotime($z[$y]))."/".$fetDevice[di_imeiId].".txt";
						$km = explode(",",kmsPerDay($path));
						if($km[0] !=0)
						{
							$getDateReading = "SELECT * FROM tb_speed_meter_info WHERE tmsi_clientId = ".$fetDevice[di_clientId]." AND tmsi_imei = '".$fetDevice[di_imeiId]."' AND tmsi_readDate = '".date('Y-m-d',strtotime($z[$y]))."'";
							$resDateReading = $db->query($getDateReading);
			
							if($db->affected_rows == 0)
							{
								
								$kmdata['tmsi_clientId'] = $fetDevice[di_clientId];
								$kmdata['tmsi_imei'] = $fetDevice[di_imeiId];
								$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($z[$y]));
								$kmdata['tmsi_kmpd'] = $km[0];
								
								//print_r($kmdata);
								//exit;
								$db->query_insert("tb_speed_meter_info", $kmdata);
							}
							else
							{
								$fetDateReading = $db->fetch_array($resDateReading);
								$kmdata['tmsi_clientId'] = $fetDevice[di_clientId];
								$kmdata['tmsi_imei'] = $fetDevice[di_imeiId];
								$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($z[$y]));
								$kmdata['tmsi_kmpd'] = $km[0];
								
								//print_r($kmdata);
								//exit;
								$db->query_update("tb_speed_meter_info", $kmdata, "tsmi_id = ".$fetDateReading[tsmi_id]);
							}
							break;
						}
						
					}
					else
					{
						
						$fp_load = chk_folder($path);
						if ($fp_load)
						{
							//echo 'else'.$z[$y]."<br>";
							//$lastPath = $path;
							$km = explode(",",kmsPerDay($path));
							/*$datDate1 = $z[$y];*/
							break;
						}
					}					
					
				}
				//print_r($km);
				$getReading = "SELECT SUM(tmsi_kmpd) as dist FROM tb_speed_meter_info WHERE tmsi_clientId = ".$fetDevice[di_clientId]." AND tmsi_imei = '".$fetDevice[di_imeiId]."' group by tmsi_imei";
				$resReading = $db->query($getReading);
				//exit;
				//print_r($km);
				if($db->affected_rows > 0 )
				{
				
					$fetReading = mysql_fetch_assoc($resReading);
					$odoMeter = $fetDevice[di_odoMeter] + $fetReading[dist];
				}
				else
				{
					$odoMeter = $fetDevice[di_odoMeter];
				}
				//echo ((strtotime(date("H:i"))-strtotime(date("H:i",strtotime($km[4]))))/60)." ".date("H:i")." ".date("H:i",strtotime($km[4]))."<br>";
				
				$diffTime = ((strtotime(date("H:i"))-strtotime(date("H:i",strtotime($km[4]))))/60);
				if( $diffTime > 0 && $diffTime < 5)
					$meterArr[] = ucfirst($fetDevice[ci_clientName]).",".$devName.",".$odoMeter.",".$renewDate.",".$km[1].",".$km[2].",".$km[3].",".$km[4].",1".",".$devImage;
				else
					$meterArr[] = ucfirst($fetDevice[ci_clientName]).",".$devName.",".$odoMeter.",".$renewDate.",".$km[1].",".$km[2].",".$km[3].",".$km[4].",2".",".$devImage;
				
			}
			else
			{
				$getReading = "SELECT SUM(tmsi_kmpd) as dist FROM tb_speed_meter_info WHERE tmsi_clientId = ".$fetDevice[di_clientId]." AND tmsi_imei = '".$fetDevice[di_imeiId]."' group by tmsi_imei";
				$resReading = $db->query($getReading);
				//exit;
				//print_r($km);
				if($db->affected_rows > 0 )
				{
				
					$fetReading = mysql_fetch_assoc($resReading);
					$odoMeter = $fetDevice[di_odoMeter] + $fetReading[dist];
				}
				else
				{
					$odoMeter = $fetDevice[di_odoMeter];
				}
				$meterArr[] = ucfirst($fetDevice[ci_clientName]).",".$devName.",".$odoMeter.",".$renewDate.",Subscription Date Expired.Please Renew the Unit,,,,0,".$devImage;
			}
			$lastPath= "";
			//echo "<br>";
		}	// While
		
		if(count($meterArr)>0)
		{
			$meterArr1 = implode("@",$meterArr);
		}
		else
		{
			$meterArr1 = "";	
		}
		
		echo $meterArr1;

	}// If
}
?>